﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using System.Collections.Specialized;
using System.Configuration;
using DevExpress.Web.ASPxCallback;
using DevExpress.Web.ASPxGridView;

namespace TireService.Website
{
    public partial class Betaling : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //if (Page.IsPostBack != true)
            //{
                try
                {

                    string paymentaction = Request.QueryString["action"].ToString();

                    if (paymentaction == string.Empty)
                    {
                        // No action exist - user has entered webpage directly

                        // Redirect user to start page
                        Response.Redirect("~/Index.aspx");
                    }

                    // Get CustomerId and Invoice
                    string customerid = Request.QueryString["cid"].ToString();
                    string invoiceid = Request.QueryString["iid"].ToString();

                    //// Testing purpose
                    //string customerid = "10033";
                    //string invoiceid = "25";
                    //string paymentaction = "2";


                    // Check action
                    if (Convert.ToInt32(paymentaction) == (int)Shared.PaymentGateWayActions.InitiatePayment)
                    {
                        // Customer is about to pay invoice

                        if (customerid == string.Empty | invoiceid == string.Empty)
                        {
                            // Throw exception
                            throw new ArgumentException("Betaling kan ikke finde sted, da faktura ikke er valgt - venligst kontakt vores kundesupport.");
                        }
                        else
                        {
                            // Validate customer
                            TireServiceDB db = new TireServiceDB();

                            Customer customer = db.GetCustomer(Convert.ToInt32(customerid));

                            if (customer == null)
                            {
                                throw new ArgumentException("Betaling kan ikke finde sted, da kunde ikke eksisterer - venligst kontakt vores kundesupport.");
                            }
                            else
                            {
                                // Validate invoice
                                EconomicInterface ecoInterface = new EconomicInterface();

                                if (!ecoInterface.InvoiceLinesExists(Convert.ToInt32(invoiceid), Convert.ToInt32(customerid)))
                                {
                                    throw new ArgumentException("Betaling kan ikke finde sted, da faktura ikke eksisterer - venligst kontakt vores kundesupport.");
                                }
                                else
                                {
                                    // Check if invoice is already paid
                                    decimal? invoiceremainder = ecoInterface.GetInvoiceRemainder(Convert.ToInt32(invoiceid), Convert.ToInt32(customerid));

                                    if (invoiceremainder > 0 & invoiceremainder != null)
                                    {
                                        // Invoice is not paid

                                        // Show correct panel
                                        pInvoiceAlreadyPaid.Visible = false;
                                        pInitiateOnlinePayment.Visible = true;
                                        pOnlinePaymentDone.Visible = false;
                                        pOnlinePaymentFailed.Visible = false;

                                        // Show customer and invoice data
                                        lCustomerInformation.Text = customer.Name + "<br>" + customer.Address + "<br>" + customer.ZipCode + " " + customer.City + "<br>" + customer.Phone1 + "<br>" + customer.Email;
                                        lInvoiceId.Text = invoiceid;

                                        lAmount.Text = string.Format("{0:N}", invoiceremainder.ToString());

                                        // Link to invoice
                                        lnkInvoice.NavigateUrl = string.Format("~/Reports/View/Faktura.aspx?CustomerId={0}&InvoiceId={1}", customer.CustomerId.ToString(), invoiceid);
                                        lnkInvoice.Text = "Faktura " + invoiceid;
                                    }
                                    else
                                    {
                                        // Invoice is already paid
                                        pInvoiceAlreadyPaid.Visible = true;
                                        pInitiateOnlinePayment.Visible = false;
                                        pOnlinePaymentDone.Visible = false;
                                        pOnlinePaymentFailed.Visible = false;

                                        // Link to invoice
                                        lnkInvoice_AlreadyPaid.NavigateUrl = string.Format("~/Reports/View/Faktura.aspx?CustomerId={0}&InvoiceId={1}", customerid, invoiceid);
                                        lnkInvoice_AlreadyPaid.Text = "Faktura " + invoiceid;
                                    }
                                }
                            }
                        }
                    }
                    
                    if (Convert.ToInt32(paymentaction) == (int)Shared.PaymentGateWayActions.PaymentCompleted)
                    {
                        // Payment has been done

                        // Get actioncode from gateway
                        string actioncode = Request.QueryString["actioncode"];

                        // HACK: Due to session value could not be found :-( (11/9-2013)
                        //// Check redirect is from payment gateway
                        //if (Convert.ToBoolean(Session["RedirectedToPaymentGateway"]) != true)
                        //{
                        //    // Throw exception
                        //    throw new ArgumentException("Siden kan ikke vises grundet viderestilling ikke kommer fra betalingsgateway - venligst kontakt vores kundesupport.");
                        //}

                        if (customerid == string.Empty | invoiceid == string.Empty)
                        {
                            // Throw exception
                            throw new ArgumentException("Siden kunne ikke vises, da kunde eller faktura ikke er valgt - venligst kontakt vores kundesupport.");
                        }
                        else
                        {
                            // Validate customer
                            TireServiceDB db = new TireServiceDB();

                            Customer customer = db.GetCustomer(Convert.ToInt32(customerid));

                            if (customer == null)
                            {
                                throw new ArgumentException("Betaling kan ikke finde sted, da kunde ikke eksisterer - venligst kontakt vores kundesupport.");
                            }
                            else
                            {
                                // Validate invoice
                                EconomicInterface ecoInterface = new EconomicInterface();

                                byte[] customerinvoice = ecoInterface.GetInvoice(Convert.ToInt32(invoiceid), Convert.ToInt32(customerid));

                                if (customerinvoice == null)
                                {
                                    throw new ArgumentException("Betaling kan ikke finde sted, da faktura ikke eksisterer - venligst kontakt vores kundesupport.");
                                }
                                else
                                {
                                    // Mark invoice as paid in E-conomic
                                    ecoInterface.CashbookInvoice(Convert.ToInt32(invoiceid), 5820, (int)Shared.EcoCashBooks.Payments);

                                    // Reset paymentgate session (to avoid double postback)
                                    Session["RedirectedToPaymentGateway"] = null;

                                    // Show confirmation on payment
                                    pInvoiceAlreadyPaid.Visible = false;
                                    pInitiateOnlinePayment.Visible = false;
                                    pOnlinePaymentDone.Visible = true;
                                    pOnlinePaymentFailed.Visible = false;

                                    // Link to invoice
                                    lnkInvoice_PaymentDone.NavigateUrl = string.Format("~/Reports/View/Faktura.aspx?CustomerId={0}&InvoiceId={1}", customerid, invoiceid);
                                    lnkInvoice_PaymentDone.Text = "Faktura " + invoiceid;

                                    // Add clientscript with google conversion tracking
                                    // TODO: Write code



                                    //http://testwebsite.mobilhjulskift.dk/Betaling.aspx?iid=37&cid=10039&action=1&transact=1017&orderid=MBH37&amount=59900&currency=208&cardtype=V-DK&transacknum=1017&actioncode=0&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=/wEPDwUKMTIzOTM4Nzk2OGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFTWN0bDAwJGN0bDAwJENvbnRlbnRQbGFjZUhvbGRlcjEkY29udGVudCRwSW5pdGlhdGVPbmxpbmVQYXltZW50JGJ0bkdvVG9QYXltZW508v6wwjeoDXf0XwTykUnxmpeyMQxzAbKHYNV6YcxvE8A=&__EVENTVALIDATION=/wEWAgKbrp2ICwKDneGLDXNzpgmBZk+TJS8Ae30eFsNQDOVZI95iwVHXjYRIeHBL&lang=da&DXScript=1_42,1_74,1_57,1_40,1_63,2_15
                                }
                            }
                        }
                    }

                    if (Convert.ToInt32(paymentaction) == (int)Shared.PaymentGateWayActions.PaymentFailed)
                    {
                        // Payment failed

                        // Get actioncode from gateway
                        string actioncode = Request.QueryString["actioncode"];
                        string errormessage = "";

                        // Show payment failed
                        pInvoiceAlreadyPaid.Visible = false;
                        pInitiateOnlinePayment.Visible = false;
                        pOnlinePaymentDone.Visible = false;
                        pOnlinePaymentFailed.Visible = true;

                        if (actioncode == "1")
                        {
                            errormessage = "Fejlkode: Transaktion blev afvist";
                        }
                        if (actioncode == "2")
                        {
                            errormessage = "Fejlkode: Mulig svindel";
                        }
                        if (actioncode == "3")
                        {
                            errormessage = "Fejlkode: Kommunikationsfejl";
                        }
                        if (actioncode == "4")
                        {
                            errormessage = "Fejlkode: Kort er udløbet";
                        }
                        if (actioncode == "5")
                        {
                            errormessage = "Fejlkode: Fejl hos PBS system";
                        }
                        if (actioncode == "6")
                        {
                            errormessage = "Fejlkode: Invalid transaktion";
                        }
                        if (actioncode == "7")
                        {
                            errormessage = "Fejlkode: System fejl";
                        }
                        if (actioncode == "8")
                        {
                            errormessage = "Fejlkode: Forkert butiksnummer";
                        }
                        if (actioncode == "9")
                        {
                            errormessage = "Fejlkode: Kort ikke fundet";
                        }
                        if (actioncode == "10")
                        {
                            errormessage = "Fejlkode: Kort nummer indtastet er for kort";
                        }
                        if (actioncode == "11")
                        {
                            errormessage = "Fejlkode: Transaktion ikke tilladt for butikshaver";
                        }
                        if (actioncode == "12")
                        {
                            errormessage = "Fejlkode: Transaktion ikke tilladt for korthaver";
                        }
                        if (actioncode == "13")
                        {
                            errormessage = "Fejlkode: Ugyldigt kortnummer";
                        }
                        if (actioncode == "14")
                        {
                            errormessage = "Fejlkode: Kortnummer indeholder ulovlige tegn";
                        }
                        if (actioncode == "15")
                        {
                            errormessage = "Fejlkode: Udløbs måned indeholder ulovlige tegn";
                        }
                        if (actioncode == "16")
                        {
                            errormessage = "Fejlkode: Udløbs år indeholder ulovlige tegn";
                        }
                        if (actioncode == "17")
                        {
                            errormessage = "Fejlkode: Sikkerhedskode indeholder ulovlige tegn";
                        }
                        if (actioncode == "18")
                        {
                            errormessage = "Fejlkode: Kortnummer er ikke autoriseret i forhold til korttype der kan betales med";
                        }
                        if (actioncode == "19")
                        {
                            errormessage = "Fejlkode: Ordre ikke unik - kan også skyldes du allerede har betalt";
                        }
                        if (actioncode == "20")
                        {
                            errormessage = "Fejlkode: Der er ikke angivet beløb på betaling";
                        }
                        if (actioncode == "21")
                        {
                            errormessage = "Fejlkode: Ikke en unik MD5 krypteringskode";
                        }
                        if (actioncode == "22")
                        {
                            errormessage = "Fejlkode: Netbank autorisation fejlede";
                        }
                        if (actioncode == "23")
                        {
                            errormessage = "Fejlkode: Netbank autorisation annulleret af kunden";
                        }
                        if (actioncode == "24")
                        {
                            errormessage = "Fejlkode: Icash betaling fejlede";
                        }
                        if (actioncode == "25")
                        {
                            errormessage = "Fejlkode: MAC hash er ugyldig";
                        }

                        lblErrorMessage.Text = errormessage;
                    }
                }
                catch (Exception ex)
                {
                    // TODO: Send email til system support om fejl

                    // Redirect user to error page

                    // Show error panel
                    pInvoiceAlreadyPaid.Visible = false;
                    pInitiateOnlinePayment.Visible = false;
                    pOnlinePaymentDone.Visible = false;
                    pOnlinePaymentFailed.Visible = false;
                    pErrorPanel.Visible = true;

                    lblError.Text = ex.Message;
                }
            //}
        }
        
        /// <summary>
        /// Callback function that redirects user to payment gateway to pay invoice
        /// </summary>
        protected void callbackInitiateOnlinePayment_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Get CustomerId and Invoice
                string customerid = Request.QueryString["cid"];
                string invoiceid = Request.QueryString["iid"];

                //// Testing purpose
                //string customerid = "10033";
                //string invoiceid = "25";

                // Customer is about to pay invoice
                if (customerid == string.Empty | invoiceid == string.Empty)
                {
                    // Throw exception
                    throw new ArgumentException("Betaling kan ikke finde sted, da faktura ikke er valgt - venligst kontakt vores kundesupport.");
                }
                else
                {
                    // Validate customer
                    TireServiceDB db = new TireServiceDB();

                    Customer customer = db.GetCustomer(Convert.ToInt32(customerid));

                    if (customer == null)
                    {
                        throw new ArgumentException("Betaling kan ikke finde sted, da kunde ikke eksisterer - venligst kontakt vores kundesupport.");
                    }
                    else
                    {
                        // Validate invoice
                        EconomicInterface ecoInterface = new EconomicInterface();

                        byte[] customerinvoice = ecoInterface.GetInvoice(Convert.ToInt32(invoiceid), Convert.ToInt32(customerid));

                        if (customerinvoice == null)
                        {
                            throw new ArgumentException("Betaling kan ikke finde sted, da faktura ikke eksisterer - venligst kontakt vores kundesupport.");
                        }
                        else
                        {
                            // Check if invoice is already paid
                            // TODO: Write code
                            string amount = string.Format("{0:N}", ecoInterface.GetInvoiceRemainder(Convert.ToInt32(invoiceid), customer.CustomerId)).Replace(".", "").Replace(",", "");
                            //string amount = string.Format("{0:N}", 50).Replace(".", "").Replace(",", "");
                            string acceptURL = Convert.ToString(ConfigurationManager.AppSettings["AcceptURL"]) + "?iid=" + invoiceid + "&cid=" + customer.CustomerId.ToString() + "&action=" + Convert.ToString((int)Shared.PaymentGateWayActions.PaymentCompleted);
                            string declineURL = Convert.ToString(ConfigurationManager.AppSettings["DeclineURL"]) + "?iid=" + invoiceid + "&action=" + Convert.ToString((int)Shared.PaymentGateWayActions.PaymentFailed);
                            
                            NameValueCollection data = HelperFunctions.OnlinePayment(amount,
                                                          invoiceid,
                                                          Convert.ToString(ConfigurationManager.AppSettings["ShopCurrency"]),
                                                          Convert.ToString(ConfigurationManager.AppSettings["ShopMd5Key"]),
                                                          Convert.ToString(ConfigurationManager.AppSettings["ShopId"]),
                                                          Convert.ToString(ConfigurationManager.AppSettings["ShopOrderPrefix"]),
                                                          Convert.ToString(ConfigurationManager.AppSettings["ShopPayType"]),
                                                          Convert.ToString(ConfigurationManager.AppSettings["ShopCardType"]),
                                                          Convert.ToString(ConfigurationManager.AppSettings["ShopLanguage"]),
                                                          acceptURL,
                                                          declineURL
                                                         );

                            string postbackForm = HttpHelper.SimplePreparePOSTForm(Convert.ToString(ConfigurationManager.AppSettings["ShopAuthURL"]), data);

                            // Set session to indicate that redirection to payment gateway has been done
                            Session["RedirectedToPaymentGateway"] = true;

                            e.Result = postbackForm;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException(ex.Message);
            }
        }

        /// <summary>
        /// Callback function that...
        /// </summary>
        protected void callbackOnlinePaymentDone_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            try
            {

            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException(ex.Message);
            }
        }

        /// <summary>
        /// Callback function that...
        /// </summary>
        protected void callbackOnlinePaymentFailed_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            try
            {

            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException(ex.Message);
            }
        }

        protected void gvInvoiceLines_CustomUnboundColumnData(object sender, ASPxGridViewColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "TotalPrice")
            {
                decimal price = (decimal)e.GetListSourceFieldValue("TotalNetAmount");
                decimal vat = (decimal)e.GetListSourceFieldValue("VatAmount");
                e.Value = price + vat;
            }
        }

    }
}